<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="35%"
    destroy-on-close
  >
    <div style="max-height: 500px; overflow: hidden; overflow-y: auto">
      <el-form
        ref="ruleFormRef"
        :rules="rules"
        :model="dialogForm"
        label-width="140px"
      >
        <el-form-item label="数据源名称：" prop="dataSourceName">
          <el-input
            v-model="dialogForm.dataSourceName"
            placeholder="请输入数据源名称"
          />
        </el-form-item>
        <el-form-item label="数据源描述：" prop="dataSourceDescription">
          <el-input
            v-model="dialogForm.dataSourceDescription"
            placeholder="请输入数据源描述"
          />
        </el-form-item>

        <el-form-item label="数据源类型：" prop="dataSourceTypeId">
          <el-select
            v-model="dialogForm.dataSourceTypeId"
            filterable
            placeholder="请选择数据源类型"
            style="width: 100%"
            @change="handleTypeSelect"
          >
            <el-option
              v-for="item in dataSourceTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="服务名称："
          prop="serviceName"
          v-if="dialogForm.dataSourceTypeId == 9"
        >
          <el-input v-model="dialogForm.serviceName" placeholder="服务名称" />
        </el-form-item>
        <el-form-item label="IP/主机名：" prop="dataSourceIp">
          <el-input v-model="dialogForm.dataSourceIp" placeholder="IP地址" />
        </el-form-item>
        <el-form-item label="端口号：" prop="dataSourcePort">
          <el-input
            v-model="dialogForm.dataSourcePort"
            placeholder="请输入端口号"
          />
        </el-form-item>
        <el-form-item label="数据库名：" prop="dataBaseName">
          <el-input
            v-model="dialogForm.dataBaseName"
            placeholder="请输入数据库名"
          />
        </el-form-item>
        <!-- 选择是4 8 9对应的musql dameng oracle类型时不用填写模式名 -->
        <el-form-item label="模式名：" prop="schemaName">
          <el-input
            v-model="dialogForm.schemaName"
            :disabled="[4, 8, 9].includes(dialogForm.dataSourceTypeId)"
            placeholder="请输入模式名"
          />
        </el-form-item>
        <el-form-item label="用户名：" prop="userName">
          <el-input
            v-model="dialogForm.userName"
            placeholder="请输入用户名"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="密码：" prop="password" class="pwd-box">
          <el-input
            v-model="dialogForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
            autocomplete="off"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="连接地址：" prop="dataBaseAddress">
          <el-input type="textarea" v-model="dialogForm.dataBaseAddress" />
        </el-form-item>

        <!-- 图谱平台暂时没有租户相关概念 隐藏所属系统 -->
        <!-- <el-form-item label="子系统：" prop="tenantId">
          <el-select
            v-model="dialogForm.tenantId"
            filterable
            placeholder="请选择子系统"
            style="width: 100%"
          >
            <el-option
              v-for="item in tenants"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item label="是否内部数据源：" prop="inside">
          <el-radio-group v-model="dialogForm.inside" class="ml-4">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="connectTest" v-loading="testLoading"
        >测试连接</el-button
      >
      <el-button type="primary" @click="confirmDialog">确定</el-button>
    </template>
  </el-dialog>
</template>
<script>
export default {
  name: "OperaDialog",
  props: {
    dataSourceTypes: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      dialogTitle: "新增数据源",
      dialogVisible: false,
      isEdit: false,
      // 子系统
      tenants: [],
      testLoading: false,
      connectFlag: 2,
      dialogForm: {
        dataSourceName: null,
        dataSourceDescription: null,
        dataSourceTypeId: null,
        dataSourceIp: null,
        dataSourcePort: null,
        dataBaseName: null,
        schemaName: null,
        userName: null,
        password: null,
        dataBaseAddress: null,
        // tenantId: null,
        inside: null,
        serviceName: "",
      },
      rules: {
        dataSourceName: [
          { required: true, message: "数据源名不能为空！", trigger: "blur" },
        ],
        dataSourceTypeId: [
          { required: true, message: "数据源不能为空!", trigger: "change" },
        ],
        dataSourceIp: [
          { required: true, message: "IP不能为空！", trigger: "blur" },
        ],
        serviceName: [
          { required: true, message: "服务名称不能为空！", trigger: "blur" },
        ],
        dataSourcePort: [
          { required: true, message: "端口号不能为空！", trigger: "blur" },
        ],
        dataBaseName: [
          { required: true, message: "数据库名不能为空！", trigger: "blur" },
        ],
        schemaName: [
          { required: true, message: "模式名不能为空！", trigger: "blur" },
        ],
        userName: [
          { required: true, message: "用户名不能为空！", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空！", trigger: "blur" },
        ],
        dataBaseAddress: [
          { required: true, message: "连接地址不能为空！", trigger: "blur" },
        ],
        // tenantId: [
        //   { required: true, message: "子系统不能为空！", trigger: "change" },
        // ],
        inside: [
          {
            required: true,
            message: "请指定是否内部数据源！",
            trigger: "change",
          },
        ],
      },
    };
  },
  // 监听连接地址组成数据
  watch: {
    "dialogForm.dataSourceTypeId": {
      handler: "makeAddress",
    },
    "dialogForm.dataSourceIp": {
      handler: "makeAddress",
    },
    "dialogForm.dataSourcePort": {
      handler: "makeAddress",
    },
    "dialogForm.dataBaseName": {
      handler: "makeAddress",
    },
  },
  methods: {
    // 打开弹窗
    openDialog(title, row) {
      // 请求子系统数据
      this.getTenantList();
      this.dialogTitle = title;
      // 新增
      this.isEdit = false;
      this.dialogForm = {
        dataSourceName: null,
        dataSourceDescription: null,
        dataSourceTypeId: null,
        dataSourceIp: null,
        dataSourcePort: null,
        dataBaseName: null,
        schemaName: null,
        userName: null,
        password: null,
        dataBaseAddress: null,
        // tenantId: null,
        inside: null,
      };
      // 编辑
      if (row) {
        this.dialogForm = row;
        // 拼接连接地址
        // 处理模式
        this.makeAddress();
        this.handleTypeSelect(row.dataSourceTypeId);
        this.isEdit = true;
      }
      this.dialogVisible = true;
    },
    // 获取子系统列表
    getTenantList() {
      this.$axios
        .get(this.$api.dataConnection.dataSource.getTenantList, {
          params: { pageSize: 100 },
        })
        .then((res) => {
          const data = res.data.data;
          if (Array.isArray(data.records)) {
            this.tenants = data.records.map((item) => {
              item.label = item.name;
              item.value = item.id;
              return item;
            });
          }
        });
    },
    // 处理连接地址
    makeAddress() {
      const sourceType = this.dataSourceTypes.find(
        (ele) => ele.value === this.dialogForm.dataSourceTypeId
      );
      const sourceTypeName = sourceType ? sourceType.label : "";
      this.dialogForm.dataBaseAddress = `${
        this.dialogForm.access ? this.dialogForm.access + ":" : ""
      }${sourceTypeName}://${this.dialogForm.dataSourceIp || ""}:${
        this.dialogForm.dataSourcePort || ""
      }/${this.dialogForm.dataBaseName || ""}${
        this.dialogForm.extra ? "?" + this.dialogForm.extra : ""
      }`;
    },
    handleTypeSelect(val) {
      // 选择mysql dameng oracle 时 清空字段 修改规则为非必填
      if ([4, 8, 9].includes(val)) {
        this.dialogForm.schemaName = null;
        this.rules.schemaName = [
          { required: false, message: "模式名不能为空！", trigger: "blur" },
        ];
      } else {
        this.rules.schemaName = [
          { required: true, message: "模式名不能为空！", trigger: "blur" },
        ];
      }
    },
    connectTest() {
      this.testLoading = true;
      this.$axios
        .post(
          this.$api.dataConnection.dataSource.testConnection,
          this.dialogForm
        )
        .then((res) => {
          const { code, message, data } = res.data;
          if (code === 200) {
            this.connectFlag = 1;
            if (data === "success") {
              this.$notify.success({
                title: "连接成功",
                message: "数据源连接测试通过， 请保存",
                showClose: false,
              });
            } else {
              this.$notify.error({
                title: "连接未成功",
                message: "数据源连接测试未通过，请检查设置信息",
                showClose: false,
              });
            }
          } else if (code === 8008) {
            this.connectFlag = 0;
            this.$message.error(message);
          }
        })
        .catch(() => {})
        .finally(() => {
          this.testLoading = false;
        });
    },
    confirmDialog() {
      if (this.isEdit) {
        const params = { ...this.dialogForm, testConnect: this.connectFlag };
        this.submitEdit(params);
      } else {
        const params = { ...this.dialogForm, testConnect: this.connectFlag };
        this.submitAdd(params);
      }
    },
    // 新增
    submitAdd(params) {
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          this.$axios
            .post(this.$api.dataConnection.dataSource.addDataSource, params)
            .then((res) => {
              this.$message.success(res.data.message);
              this.$emit("reload");
              this.dialogVisible = false;
            });
        } else {
          return false;
        }
      });
    },
    // 编辑
    submitEdit(params) {
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          if (!params.password) {
            delete params.password;
          }
          this.$axios
            .post(this.$api.dataConnection.dataSource.editDataSource, params)
            .then((res) => {
              this.$message.success(res.data.message);
              this.$emit("reload");
              this.dialogVisible = false;
            });
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style scoped></style>
